package top.omooo.testlogin;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements TextWatcher{
private TextInputLayout mInputLayoutUsername;
private TextInputLayout mInputLayoutPwd;
private Button mButtonLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mInputLayoutUsername = findViewById(R.id.inputLayoutUsername);
mInputLayoutPwd = findViewById(R.id.inputLayoutPassword);
mButtonLogin = findViewById(R.id.btn_login);
mButtonLogin.setClickable(false);
mInputLayoutUsername.getEditText().addTextChangedListener(this);
mInputLayoutPwd.getEditText().addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
boolean hasErrorUsername;
boolean hasErrorPwd;
int counter = mInputLayoutUsername.getEditText().getText().toString().length();
if (counter < 4) {
mInputLayoutUsername.setErrorEnabled(true);
mInputLayoutUsername.setError("用户名不能低于四位");
hasErrorUsername = true;
} else if (counter > 8) {
mInputLayoutUsername.setErrorEnabled(true);
mInputLayoutUsername.setError("用户名不能大于八位");
hasErrorUsername = true;
}else {
mInputLayoutUsername.setErrorEnabled(false);
hasErrorUsername = false;
}
int counter1 = mInputLayoutPwd.getEditText().getText().toString().length();
if (counter1 < 6) {
mInputLayoutPwd.setErrorEnabled(true);
mInputLayoutPwd.setError("密码不能低于六位");
hasErrorPwd = true;
} else if (counter1 > 16) {
mInputLayoutPwd.setErrorEnabled(true);
mInputLayoutPwd.setError("密码不能大于十六位");
hasErrorPwd = true;
}else {
mInputLayoutPwd.setErrorEnabled(false);
hasErrorPwd = false;
}
if (hasErrorPwd||hasErrorUsername) {
mButtonLogin.setClickable(false);
} else {
mButtonLogin.setClickable(true);
}
}
}